package spring.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 使用cglib返回代理对象
 */
public class CglibProxy2 implements MethodInterceptor {

    Object target;

    Object getProxy(Object target){
        this.target = target;

        Enhancer enhancer = new Enhancer();

        // 设置父类
        enhancer.setSuperclass(target.getClass());
        // 设置回调（这里自己实现了）
        enhancer.setCallback(this);
        // 设置类加载器
        enhancer.setClassLoader(target.getClass().getClassLoader());

        // 生成代理对象
        return enhancer.create();

    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        Object result = null;

        List<Advice> advices = new ArrayList<>();
        advices.add(new BeforeAdvice());
        advices.add(new AfterAdvice());

        Chain chain = new Chain(advices, method, args ,target);
        chain.proceed();

        return result;
    }
}
